package com.lh.java.jsp.postandget;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import com.lh.log.log4j.StaticLogOptimize;

/**
 ************************************************
 ** Module : 模拟get和post请求
 ** Date: 2013-3-27  Time: 下午04:31:56 
 ** Author lh 
 ************************************************ 
 */
public class TestImitatePostAndGet {
	
	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			try {
				TestImitatePostAndGet.get();
				StaticLogOptimize.debug("i="+i +"is run ");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public static void post(int i) throws Exception{ 
	    String s = UUID.randomUUID().toString(); 
	    String s1 = s.substring(0,2); 
	    s = s1+ s.substring(s.length() - 3, s.length()); 
	     
	    URL url = new URL("http://192.168.1.37:8080/newads1/funcInfo.action?s={a:1,b:2,c:5}");// 提交地址 
	    StaticLogOptimize.debug("i am is get ");
	    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
	    httpURLConnection.setDoOutput(true);// 打开写入属性 
	    httpURLConnection.setDoInput(true);// 打开读取属性 
	    httpURLConnection.setRequestMethod("POST");// 设置提交方法 POST
	    httpURLConnection.setConnectTimeout(50000);// 连接超时时间 
	    httpURLConnection.setReadTimeout(50000); 
	    httpURLConnection.connect(); 
	     
	    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "GBK")); 
	    out.write("t=" + s + i +  //用户名不能重复 
	        "&s=" +"{a:1,b:2,c:5}"+ 
	        "&sex=日你很行" + 
	        "&oicq=748748" + 
	        "&icq=748748" + 
	        "&msn=caonima");//要post的数据，多个以&符号分割 
	    out.flush(); 
	    out.close();  
	}
	
	public static void get() throws IOException{
		URL url = new URL("http://192.168.1.37:8080/newads1/funcInfo.action?s={a:1,b:2,c:5}");
		InputStream in = url.openStream();
		BufferedReader bin = new BufferedReader(new InputStreamReader(in, "UTF-8"));
		String s = null;
		while((s=bin.readLine())!=null){
			System.out.println(s);
		}
		bin.close();
	}
	
	  //读取post之后的返回值 
//  BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) httpURLConnection.getInputStream())); 
//  String line = null; 
//  StringBuilder sb = new StringBuilder(); 
//  while ((line = in.readLine()) != null) { 
//    sb.append(line); 
//  } 
//  in.close(); 
//  System.out.println("client:" + sb.toString()); 
   
//  httpURLConnection.disconnect();//断开连接 
//
//  // 
//  System.out.println("client post ok:" + i); 
//}  

}
